package com.dolawing.exoplayerdemo2;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.DefaultTimeBar;
import com.google.android.exoplayer2.ui.TimeBar;
import com.google.android.exoplayer2.util.Util;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;

import java.util.List;

public class MainActivity extends AppCompatActivity implements ExoPlayerService.OnProgressLis{

    private DefaultTimeBar timeBar;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private ImageView ivStop , next15S , previous15s ,ivSpeed;
    private ExoPlayerService mService;

    private Intent serviceIntent;
    private ServiceConnection serviceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initWidget();
        bestPermissionX();
    }

    private void initView(){
        timeBar = findViewById(R.id.exo_progress_bar);
        tvStartTime = findViewById(R.id.tv_start_time);
        tvEndTime = findViewById(R.id.tv_end_time);
        ivStop = findViewById(R.id.iv_audio_switch);
        next15S = findViewById(R.id.iv_music_next);
        previous15s = findViewById(R.id.iv_music_previous);
        ivSpeed = findViewById(R.id.iv_audio_speed);
        //快进15S
        next15S.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ExoPlayerManager.getDefault().isPaused()) {
                    ExoPlayerManager.getDefault().seekToTimeBarPosition2(15000);
                }
            }
        });
        //后退15S
        previous15s.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ExoPlayerManager.getDefault().isPaused()) {
                    ExoPlayerManager.getDefault().seekToTimeBarPosition2(-15000);
                }
            }
        });
        //倍数播放
        final boolean[] flag = {true};
        ivSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ExoPlayerManager.getDefault().isPaused() && flag[0]==true) {
                    flag[0] = false;
                    ExoPlayerManager.getDefault().setPlaySpeed(2.0f);
                }else{
                    flag[0] = true;
                    ExoPlayerManager.getDefault().setPlaySpeed(1.0f);
                }
            }
        });
        //播放与暂停
        ivStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ExoPlayerManager.getDefault().isPaused()) {
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
                    ExoPlayerManager.getDefault().pauseRadio();
                } else {
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_play);
                    ExoPlayerManager.getDefault().resumeRadio();
                }
            }
        });
    }

    private void initWidget() {
        ExoPlayerManager.getDefault().init(this);
        bindService();

        timeBar.addListener(new TimeBar.OnScrubListener() {
            @Override
            public void onScrubStart(TimeBar timeBar, long position) {
                tvStartTime.setText(Util.getStringForTime(ExoPlayerManager.getDefault().getFormatBuilder()
                        , ExoPlayerManager.getDefault().getFormatter(), position));
            }

            @Override
            public void onScrubMove(TimeBar timeBar, long position) {
                LogUtil.i("position="+position);
                ExoPlayerManager.getDefault().seekToTimeBarPosition(position);
            }

            @Override
            public void onScrubStop(TimeBar timeBar, long position, boolean canceled) {

            }
        });
    }

//
//    @Override
//    public void onBackPressed() {
//        /*这是重点*/
//        moveTaskToBack(true);
//    }

    private void bindService() {
        LogUtil.i("bindService");
        serviceIntent = new Intent(MainActivity.this, ExoPlayerService.class);
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((ExoPlayerService.MusicBinder) service).getService();
//                    String uri = "https://storage.googleapis.com/exoplayer-test-media-0/play.mp3";
                    mService.setOnProgressLis(MainActivity.this).initListener();
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            /*模仿网络请求*/
                            LogUtil.d("发送请求");
                            String uri = "https://storage.googleapis.com/exoplayer-test-media-0/play.mp3";
//                            String uri ="https://v26-web.douyinvod.com/e942be62dc93493680ee938b40dbd6cb/6374fdb8/video/tos/cn/tos-cn-ve-15c001-alinc2/oIWtIAbeCdUQru91AzgEIteDKqwAKj0MnpALBP/?a=6383&ch=5&cr=3&dr=0&lr=all&cd=0%7C0%7C0%7C3&cv=1&br=1791&bt=1791&cs=0&ds=4&ft=LjhJEL998xXYu4hm_0P58lZW_3iX2mLtOVJEtnzEjCPD-Ani&mime_type=video_mp4&qs=0&rc=ZmloZmY8ODhlZ2c2ZWVmM0BpajNsaTc6ZmZlZzMzNGkzM0BeMDBhYi9jNmExMTJjLTA2YSNpbmRfcjRvX25gLS1kLS9zcw%3D%3D&l=2022111622081101021214522610003DB1&btag=28000";
                            ExoPlayerManager.getDefault().loadUriRadio(uri);
                        }
                    }, 1000);
                }
                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
            startService(serviceIntent);
        }
    }

    private void unbindService() {
        if (null != serviceConnection) {
            unbindService(serviceConnection);
            serviceConnection = null;
        }
    }


    @Override
    protected void onDestroy() {
        unbindService();
        super.onDestroy();
    }

    @Override
    public void onPositionChanged(long curPositionTime) {
        if (timeBar != null)
            timeBar.setPosition(curPositionTime);
    }

    @Override
    public void onDurationChanged(long durationTime) {
        if (timeBar != null)
            timeBar.setDuration(durationTime);
    }

    @Override
    public void onBufferedPositionChanged(long bufferedPosition) {
        if (timeBar != null)
            timeBar.setBufferedPosition(bufferedPosition);
    }

    @Override
    public void onCurTimeStringChanged(String curTimeString) {
        if (tvStartTime != null) {
            tvStartTime.setText(curTimeString);
        }

    }

    @Override
    public void onDurationTimeStringChanged(String durationTimeString) {
        if (tvEndTime != null) {
            tvEndTime.setText(durationTimeString);
        }

    }

    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        LogUtil.i("onPlayerStateChanged");
        if (playWhenReady) {
            switch (playbackState) {
                case Player.STATE_READY:
                    LogUtil.d("----time5");
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_play);
                    ExoPlayerManager.getDefault().setPaused(false);
                    break;
                case Player.STATE_ENDED:
                    /*如果是节，播放下一首*/
                    LogUtil.i("播放下一首");
                    break;
                default:
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
                    ExoPlayerManager.getDefault().setPaused(true);
                    break;

            }
        } else {
            ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
            ExoPlayerManager.getDefault().setPaused(true);
        }
    }


    /**
     * 开通权限
     */
    private void bestPermissionX(){
        PermissionX.init(this)
                .permissions(Manifest.permission.INTERNET, Manifest.permission.READ_PHONE_STATE)
                .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
                .onExplainRequestReason(
                        new ExplainReasonCallbackWithBeforeParam() {
                            @Override
                            public void onExplainReason(ExplainScope scope, List<String> deniedList, boolean beforeRequest) {
                                scope.showRequestReasonDialog(deniedList, "即将申请的权限是程序必须依赖的权限", "确定","取消");

                            }
                        }).request(new RequestCallback(){
            @Override
            public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                if (allGranted) {
                    Toast.makeText(MainActivity.this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "您拒绝了如下权限：" + deniedList, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
